package com.pshcp.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.framework.base.PageList;
import com.framework.base.ResultBuilder;
import com.framework.base.ResultDTO;
import com.framework.tool.CommonTool;
import com.github.pagehelper.PageHelper;
import com.pshcp.common.enums.CommonStatusEnum;
import com.pshcp.domain.dto.PatientUserDTO;
import com.pshcp.domain.model.PatientUser;
import com.pshcp.mapper.PatientUserMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 患者用户表 服务实现类
 * </p>
 *
 * @author auto generator
 * @since 2022-11-02
 */
@Service
public class PatientUserService {

    @Autowired
    private PatientUserMapper patientUserMapper;

    public PatientUser getPatientUserByPhone(String phone) {
        Example example = new Example(PatientUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("phone", phone);
        criteria.andEqualTo("status", CommonStatusEnum.INIT.getCode());
        List<PatientUser> list = patientUserMapper.selectByExample(example);
        return CollectionUtils.isEmpty(list) ? null : list.get(0);
    }

    public PatientUser getPatientUserByOpenid(String openid) {
        Example example = new Example(PatientUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("openid", openid);
        criteria.andEqualTo("status", CommonStatusEnum.INIT.getCode());
        List<PatientUser> list = patientUserMapper.selectByExample(example);
        return CollectionUtils.isEmpty(list) ? null : list.get(0);
    }

    public PatientUser getPatientUserByOpenidDy(String openidDy) {
        Example example = new Example(PatientUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("openidDy", openidDy);
        criteria.andEqualTo("status", CommonStatusEnum.INIT.getCode());
        List<PatientUser> list = patientUserMapper.selectByExample(example);
        return CollectionUtils.isEmpty(list) ? null : list.get(0);
    }

    public PageList<PatientUser> list(PatientUserDTO patientUserDTO) {
        if (patientUserDTO.getPageNum() != null && patientUserDTO.getPageSize() != null) {
            PageHelper.startPage(patientUserDTO.getPageNum(), patientUserDTO.getPageSize());
        }
        Example example = new Example(PatientUser.class);
        Example.Criteria criteria = example.createCriteria();
        if (patientUserDTO.getStatus() != null) {
            criteria.andEqualTo("status", patientUserDTO.getStatus());
        }
        example.setOrderByClause(" created_time desc");
        List<PatientUser> list = patientUserMapper.selectByExample(example);
        return CommonTool.buildPageList(list);
    }

    public List<PatientUser> select(PatientUser patientUser) {
        return patientUserMapper.select(patientUser);
    }

    public Long insert(PatientUser patientUser) {
        patientUser.setStatus(CommonStatusEnum.INIT.getCode());
        patientUser.setCreatedTime(new Date());
        patientUserMapper.insert(patientUser);
        return patientUser.getId();
    }

    public int update(PatientUser patientUser) {
        patientUser.setUpdateTime(new Date());
        return patientUserMapper.updateByPrimaryKeySelective(patientUser);
    }

    public PatientUser findById(Long id) {
        return patientUserMapper.selectByPrimaryKey(id);
    }

    public List<PatientUser> findByIds(List<Long> ids) {
        Example example = new Example(PatientUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", ids);
        return patientUserMapper.selectByExample(example);
    }

    public int delById(Long id) {
        Example example = new Example(PatientUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", id);

        PatientUser patientUser = new PatientUser();
        patientUser.setStatus(CommonStatusEnum.DEL.getCode());
        return patientUserMapper.updateByExampleSelective(patientUser, example);
    }


    // 获取抖音的openId
    public JSONObject getOpenIdDouYin(String code, String anonymousCode) {
        // 获取token
        String url = "https://developer.toutiao.com/api/apps/v2/jscode2session";
        Map<String, Object> params = new HashMap<>();
        params.put("appid", "tt33db4566ace467ca01");
        params.put("secret", "94a916288ba2f70c5c5613be4a9f76e748f806a4");
        params.put("anonymous_code", anonymousCode);
        params.put("code", code);
        String postResult = sendPost(url, params);
        if(StringUtils.isEmpty(postResult)){
            return null;
        }
        JSONObject result = JSON.parseObject(postResult);
        if (result == null || result.get("err_no") == null || !"0".equals(result.get("err_no").toString())) {
            return null;
        }
        JSONObject dataResult = JSON.parseObject(result.get("data").toString());
        return dataResult;
    }

    private String sendPost(String url, Map<String, Object> params){
        try{
            // 用于保存第三方公司定义的json格式的返回结果数据
            String result = "";
            String jsonMap = JSON.toJSONString(params);
            // 创建httpclient对象
            CloseableHttpClient client = HttpClients.createDefault();
            // 创建post方式请求对象
            HttpPost httpPost = new HttpPost(url);
            // 设置参数到请求对象中
            StringEntity entity = new StringEntity(jsonMap, "UTF-8");
            /*entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");*/
            httpPost.setEntity(entity);
            // 执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                // 网络连接正常，将结果赋给result对象，此时result 对象保存的就是第三方公司定义的json格式的返回结果数据
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(result);
            }
            // 释放链接
            response.close();
            return result;
        }catch (Exception e){
            return null;
        }
    }
}
